import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

// 权限
import { getRoleJson, _getRoleList } from '../src/roleList'
import { asyncRouterMap } from '../src/router/index'


NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 注册页面要写进去
const whiteList = ['/login', '/register'] // no redirect whitelist

// 导航前置守卫
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  // console.log(to.path,"to.path");

  if (to.path.toLowerCase() == '/login' || to.path.toLowerCase() == '/register') {
    next();
  } else {
    let { state, commit } = store
    if (state.isAddRouter) {
      next();
    }
    // 如果没添加
    else {
      try {
        let token = localStorage.getItem("roleInfo");
        if (token) {
          // 从接口获取权限列表
          let roleList = await getRoleJson(token);
          let list = _getRoleList(asyncRouterMap, roleList);
          router.addRoutes(list);
          // 改变状态，表示已经配置过权限
          commit("update", { name: "isAddRouter", value: true });
          // 把筛选后的权限存入vuex里，用于渲染左侧菜单
          commit("update", { name: "asyncRoutes", value: list });
          next({ path: list[0].children[0].path });
        } else {
          next({ path: "/login" });
        }
      } catch (e) {
        next({ path: "/login" });
      }
    }
  }
  // determine whether the user has logged in
  // const hasToken = getToken()

  // if (hasToken) {
  //   if (to.path === '/login') {
  //     // if is logged in, redirect to the home page
  //     next({ path: '/' })
  //     NProgress.done()
  //   } else {
  //     const hasGetUserInfo = store.getters.name
  //     if (hasGetUserInfo) {
  //       next()
  //     } else {
  //       try {
  //         // get user info
  //         await store.dispatch('user/getInfo')
  //         next()
  //       } catch (error) {
  //         // remove token and go to login page to re-login
  //         await store.dispatch('user/resetToken')
  //         Message.error(error || 'Has Error')
  //         next(`/login?redirect=${to.path}`)
  //         NProgress.done()
  //       }
  //     }
  //   }
  // } else {
  //   /* has no token*/

  //   if (whiteList.indexOf(to.path) !== -1) {
  //     // in the free login whitelist, go directly
  //     next()
  //   } else {
  //     // other pages that do not have permission to access are redirected to the login page.
  //     next(`/login?redirect=${to.path}`)
  //     NProgress.done()
  //   }
  // }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
